package com.ysw.config;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.connection.ConnectionPoolSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MongoConfig
 * @Description TODO
 * @Author ysw
 * @Date 2021/11/3 20:34
 */
@Configuration
public class MongoConfig {
    private static final Logger logger = LoggerFactory.getLogger(MongoConfig.class);
    // 覆盖容器中默认的MongoDatabaseFactory
    @Bean

    public MongoDatabaseFactory mongoDatabaseFactory() {
        return new SimpleMongoClientDatabaseFactory(mongoClient(), "mongo_test");
    }
    @Bean
    public MongoClient mongoClient() {

        // 使用更高级的配置MongoClientSettings（请注意，这些不是建议值）
        // 配置连接认证
        MongoCredential credential = MongoCredential.createCredential("ysw_normal", "mongo_test", "java".toCharArray());
        MongoClientSettings settings = MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString("mongodb://192.168.37.11:27017")).credential(credential)
                .applyToConnectionPoolSettings(builder -> ConnectionPoolSettings.builder()
                        .maxConnectionLifeTime(10, TimeUnit.SECONDS)
                        .maxWaitTime(15, TimeUnit.SECONDS)
                        .maxConnectionIdleTime(30, TimeUnit.SECONDS)
                        .maintenanceFrequency(10, TimeUnit.SECONDS)
                        .maintenanceInitialDelay(11, TimeUnit.SECONDS)
                        .minSize(10)
                        .maxSize(20)
                        .build())
                .build();
        return MongoClients.create(settings);
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoDatabaseFactory());
    }
}